#include"../logs/lyzlog.h"

enum class TimeGap
{
    GAP_SECOND, // 按秒滚动
    GAP_MINUTE, // 按分钟滚动
    GAP_HOUR,   // 按小时滚动
    GAP_DAY     // 按天滚动
};


class RollByTimeSink : public lyzlog::LogSink  // <-- 公有继承
{
public:
    // 构造函数：初始化基础文件名和时间间隔类型
    RollByTimeSink(const std::string &basename, TimeGap gap_type)
        : _basename(basename), _ofs(), _cur_gap(0)
    {
        // 根据 gap_type 设置时间步长
        switch (gap_type) {
            case TimeGap::GAP_SECOND: _gap_size = 1; break;
            case TimeGap::GAP_MINUTE: _gap_size = 60; break;
            case TimeGap::GAP_HOUR:   _gap_size = 3600; break;
            case TimeGap::GAP_DAY:    _gap_size = 3600 * 24; break;
        }

        _cur_gap = now() / _gap_size; // 当前时间属于哪段区间

        // 创建并打开第一个日志文件
        std::string filename = createNewFile();
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    // 析构函数：关闭当前文件流
    ~RollByTimeSink() override {
        if (_ofs.is_open()) {
            _ofs.close();
        }
    }

    // **实现 LogSink 的纯虚函数**:
    //   父类中声明: virtual void log(const char *data, size_t len) = 0;
    void log(const char *data, size_t len) override {
        time_t cur = now();
        size_t gap = cur / _gap_size;

        // 如果跨过了当前区间, 说明要滚动文件
        if (gap != _cur_gap) {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = gap;
        }

        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    // 获取当前时间戳
    time_t now() {
        return std::time(nullptr);
    }

    // 生成新的日志文件名
    std::string createNewFile() {
        time_t t = now();
        struct tm lt;
        localtime_r(&t, &lt);

        std::stringstream ss;
        ss << _basename << "_";
        ss << (lt.tm_year + 1900) << "-";
        ss << (lt.tm_mon + 1) << "-";
        ss << lt.tm_mday << "_";
        ss << lt.tm_hour << "-";
        ss << lt.tm_min << "-";
        ss << lt.tm_sec << ".log";
        return ss.str();
    }

private:
    std::string   _basename;
    std::ofstream _ofs;
    size_t        _gap_size;
    size_t        _cur_gap;
};


int main()
{ 
    std::unique_ptr<lyzlog::LoggerBuilder> builder(new lyzlog::GlobalLoggerBuilder);
    builder->BuilderFormatter("[%c][%f:%l]%m%n");
    builder->BuilderLogName("lyz-Asynclog");
    builder->BuilderType(lyzlog::LoggerType::Async_log);
    builder->BuilderLimitLev(lyzlog::Loglevel::value::DEBUG);
    builder->BuilderSink<RollByTimeSink>("./logfile/Roll-Asyn-By-Time.log",TimeGap::GAP_SECOND);
    lyzlog::Logger::ptr logger = builder->Build();
    size_t cur = lyzlog::util::Date::now();
    while(lyzlog::util::Date::now() < cur + 5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }

    //test_logger("lyz-Asynclog");
    return 0;
}